package com.baidu.aip.unit.parser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidu.aip.unit.exception.UnitError;
import com.baidu.aip.unit.model.response.CommunicateResponse;
import com.baidu.aip.unit.model.response.UnitResponse;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class CommunicateParser implements Parser<CommunicateResponse> {
	
	private static final Logger Log = LoggerFactory.getLogger(CommunicateParser.class);
	
	@Override
    public CommunicateResponse parse(String json) throws UnitError {
        Log.debug("CommunicateParser:" + json);
        try {
            Gson gson = new GsonBuilder()
            	    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            	    .create();
            UnitResponse response = gson.fromJson(json, UnitResponse.class);
            
            if (response.getErrorCode() != 0) {
            	Log.error("平台返回错误:{}", response.getErrorMsg());
            	UnitError error = new UnitError(response.getErrorCode(), response.getErrorMsg());
                throw error;
            }
            
            response.setJsonRes(json);
            
            return response.getResult();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            UnitError error = new UnitError(UnitError.ErrorCode.JSON_PARSE_ERROR, "Json parse error:" + json, e);
            throw error;
        }
    }

}
